package com.java.simple.study.juc.p3.exercise;

import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Vector;

/**
 * @author zhoujl
 * @date 2022/5/7 22:04
 * @desc
 */
@Slf4j(topic = "c.ExerciseSell")
public class ExerciseSell {

    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            log.debug("第{}次测试", i);
            solve();
            log.debug("===========");
        }
    }


    public static void solve() {
        int initCount = 200000;
        TicketWindow ticketWindow = new TicketWindow(initCount);
        List<Thread> list = new ArrayList<>();
        List<Integer> sellCount = new Vector<>();
        for (int i = 0; i < 20000; i++) {
            Thread t = new Thread(() -> {
                // 主要分析这里的竞态条件
                int sell = ticketWindow.sell(randomAmount());
                //这里Vector保证线程安全
                sellCount.add(sell);
            });
            list.add(t);
            t.start();
        }

        list.forEach(t -> {
            try {
                t.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        int sellCountResult = sellCount.stream().mapToInt(Integer::intValue).sum();
        log.debug("结果:" + (initCount == (sellCountResult + ticketWindow.getCount())));
    }

    static Random random = new Random();

    public static int randomAmount() {
        return random.nextInt(5) + 1;
    }

}


class TicketWindow {

    private int count;

    public TicketWindow(int count) {
        this.count = count;
    }

    public /*synchronized*/ int getCount() {
        return count;
    }

    public synchronized int sell(int amount) {
        if (this.count >= amount) {
            this.count -= amount;
            return amount;
        } else {
            return 0;
        }
    }

}
